<template>
  <div>
    <van-search v-model="key" @input="search" placeholder="请输入搜索关键词" />
    <!-- 热门搜索 -->
    <div v-if="key == ''" class="search_wrap">
      <p class="hot_title">热门搜索</p>

      <div class="hot_name_wrap"></div>
      <span
        v-for="(item, index) in hotList"
        :key="index"
        class="hot_item"
        @click="search(item.searchWord)"
        >{{ item.searchWord }}</span
      >
    </div>

    <!-- 搜索结果 -->
    <div v-else class="search_wrap">
      <p class="hot_title">最佳匹配</p>
      <van-cell-group>
        <musicCell
          v-for="item in resultList"
          :key="item.id"
          :title="item.name"
          :id="item.id"
          :label="item.artists[0].name + '-' + item.name"
        />
      </van-cell-group>
    </div>
  </div>
</template>

<script>
import { hotAPI, searchAPI } from "@/api";
import musicCell from "@/components/musicCell.vue";
export default {
  components: { musicCell },
  data() {
    return {
      key: "",
      hotList: [],
      resultList: [],
      //保存定时器的id
      timer: null,
    };
  },
  methods: {
    search(name) {
      //点击的名字给搜索框
      this.key = name;
      //防抖关闭定时器
      clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        //根据搜索查结果
        if (this.key != "") {
          let res = await searchAPI({ keywords: this.key });
          //  console.log(res);

          this.resultList = res.data.result.songs;
        }
      }, 200);
    },
  },

  async created() {
    let res = await hotAPI();
    // console.log(res);
    this.hotList = res.data.data;
    // console.log(this.hotList);
  },
};
</script>

<style>
/* 搜索容器的样式 */
.search_wrap {
  padding: 10px;
}

/*热门搜索文字标题样式 */
.hot_title {
  font-size: 10px;
  color: #666;
}

/* 热搜词_容器 */
.hot_name_wrap {
  margin: 10px 10px;
}

/* 热搜词_样式 */
.hot_item {
  display: inline-block;
  height: 20px;
  margin-right: 5px;
  margin-bottom: 5px;
  padding: 15px 20px;
  font-size: 8px;
  line-height: 20px;
  color: #333;
  border-color: #d3d4da;
  border-radius: 20px;
  border: 1px solid #d3d4da;
}
</style>